# -*- coding: utf-8 -*-
# scripts/health_check.py
"""
系统健康检查脚本
"""

import asyncio
import sys
import os
import sqlite3
from pathlib import Path
import json
import requests
from datetime import datetime

# 添加项目路径
sys.path.append(str(Path(__file__).parent.parent))

from config.settings import settings

class HealthChecker:
    """系统健康检查器"""
    
    def __init__(self):
        self.checks = []
        self.results = {}
    
    async def run_all_checks(self):
        """运行所有检查"""
        print("🔍 开始系统健康检查...")
        print("=" * 50)
        
        checks = [
            ("Python环境", self.check_python_env),
            ("依赖包", self.check_dependencies),
            ("配置文件", self.check_config),
            ("数据库", self.check_database),
            ("API连接", self.check_api_connections),
            ("文件权限", self.check_permissions),
            ("内存使用", self.check_memory),
            ("磁盘空间", self.check_disk_space)
        ]
        
        for name, check_func in checks:
            try:
                result = await check_func()
                status = "✅" if result["status"] == "ok" else "❌"
                print(f"{status} {name}: {result['message']}")
                self.results[name] = result
            except Exception as e:
                print(f"❌ {name}: 检查失败 - {str(e)}")
                self.results[name] = {"status": "error", "message": str(e)}
        
        print("=" * 50)
        self.print_summary()
        self.save_report()
    
    async def check_python_env(self):
        """检查Python环境"""
        version = sys.version_info
        if version.major >= 3 and version.minor >= 8:
            return {"status": "ok", "message": f"Python {version.major}.{version.minor}.{version.micro}"}
        else:
            return {"status": "error", "message": f"Python版本过低: {version.major}.{version.minor}"}
    
    async def check_dependencies(self):
        """检查依赖包"""
        try:
            import streamlit
            import langchain
            import openai
            import anthropic
            
            return {"status": "ok", "message": "所有核心依赖已安装"}
        except ImportError as e:
            return {"status": "error", "message": f"缺少依赖: {e}"}
    
    async def check_config(self):
        """检查配置文件"""
        env_file = Path(".env")
        if env_file.exists():
            return {"status": "ok", "message": "配置文件存在"}
        else:
            return {"status": "warning", "message": "未找到.env配置文件"}
    
    async def check_database(self):
        """检查数据库"""
        try:
            db_path = Path("data/app.db")
            if db_path.exists():
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                cursor.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table'")
                table_count = cursor.fetchone()[0]
                conn.close()
                return {"status": "ok", "message": f"数据库正常，包含{table_count}个表"}
            else:
                return {"status": "warning", "message": "数据库文件不存在，将自动创建"}
        except Exception as e:
            return {"status": "error", "message": f"数据库错误: {e}"}
    
    async def check_api_connections(self):
        """检查API连接"""
        try:
            # 这里应该检查实际的API连接
            # 为了示例，我们只检查环境变量是否设置
            api_keys = {}
            if os.getenv("OPENAI_API_KEY"):
                api_keys["OpenAI"] = "已配置"
            if os.getenv("ANTHROPIC_API_KEY"):
                api_keys["Anthropic"] = "已配置"
            if os.getenv("GOOGLE_API_KEY"):
                api_keys["Google"] = "已配置"
            
            if api_keys:
                key_list = ", ".join(api_keys.keys())
                return {"status": "ok", "message": f"API密钥已配置: {key_list}"}
            else:
                return {"status": "warning", "message": "未配置任何API密钥"}
        except Exception as e:
            return {"status": "error", "message": f"API检查失败: {e}"}
    
    async def check_permissions(self):
        """检查文件权限"""
        try:
            data_dir = Path("data")
            if data_dir.exists() and os.access(data_dir, os.W_OK):
                return {"status": "ok", "message": "数据目录可写"}
            else:
                return {"status": "error", "message": "数据目录无写入权限"}
        except Exception as e:
            return {"status": "error", "message": f"权限检查失败: {e}"}
    
    async def check_memory(self):
        """检查内存使用"""
        try:
            import psutil
            memory = psutil.virtual_memory()
            used_percent = memory.percent
            
            if used_percent < 80:
                return {"status": "ok", "message": f"内存使用率: {used_percent:.1f}%"}
            else:
                return {"status": "warning", "message": f"内存使用率偏高: {used_percent:.1f}%"}
        except ImportError:
            return {"status": "warning", "message": "未安装psutil，无法检查内存"}
        except Exception as e:
            return {"status": "error", "message": f"内存检查失败: {e}"}
    
    async def check_disk_space(self):
        """检查磁盘空间"""
        try:
            import shutil
            total, used, free = shutil.disk_usage(".")
            free_gb = free // (1024**3)
            
            if free_gb > 1:
                return {"status": "ok", "message": f"可用空间: {free_gb}GB"}
            else:
                return {"status": "warning", "message": f"磁盘空间不足: {free_gb}GB"}
        except Exception as e:
            return {"status": "error", "message": f"磁盘检查失败: {e}"}
    
    def print_summary(self):
        """打印检查摘要"""
        total = len(self.results)
        ok_count = sum(1 for r in self.results.values() if r["status"] == "ok")
        warning_count = sum(1 for r in self.results.values() if r["status"] == "warning")
        error_count = sum(1 for r in self.results.values() if r["status"] == "error")
        
        print(f"📊 检查摘要:")
        print(f"   总计: {total}")
        print(f"   ✅ 正常: {ok_count}")
        print(f"   ⚠️  警告: {warning_count}")
        print(f"   ❌ 错误: {error_count}")
